const { app, ipcMain, BrowserWindow , Menu} = require('electron');
const { join } = require('path');
const path = require("path");
const dotenv = require('dotenv');

dotenv.config(); // 加载.env文件

process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true';

const createWindow = () => {
    const win = new BrowserWindow({
        icon: join(__dirname, 'resource/shortcut.ico'),
        width: 1080,
        height: 720,
        minWidth: 800,
        minHeight: 600,
        roundedCorners: true,

        webPreferences: {
            preload: path.join(__dirname, 'preload.js'),

            // contentSecurityPolicy: "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:;",
        }
    });


    if (process.env.VITE_DEV_SERVER_URL) {
        console.log("start >>> win.loadUrl = ",process.env.VITE_DEV_SERVER_URL)
        win.loadURL(process.env.VITE_DEV_SERVER_URL);
    } else {
        console.log("start >>> win.loadFile = dist/index.html" )
        win.loadFile(join(__dirname, 'dist/index.html'));
    }

    win.webContents.openDevTools();


    // 监听页面加载完成事件
    win.webContents.on('did-finish-load', () => {
        // console.log(">> token1 = ",db.get('token').value())
        // console.log(">>> access_token = "+db.get('token').get("access_token").value())
        // 发送验证token事件
        win.webContents.send('verify-token');
    });

    ipcMain.handle("login", (event,token) =>{
        console.log("【main】i am fun login.")
        // db.get('token').set('access_token', token.access_token);
        // db.get('token').set('refresh_token', token.refresh_token);
        // var token1 = db.get('token');
        console.log(">> token = ",token)
    })

    ipcMain.handle("logout", (event) =>{
        console.log("【main】i am fun logout. ")
    })

    ipcMain.handle("send-message", (event, message) =>{
        console.log("【main】to send-message : ",message)
        //真正的发送消息到ws
        if (typeof message === 'object' && message!== null) {
            websocket?.send(JSON.stringify(message));
        }
    })

};

Menu.setApplicationMenu(null)

let websocket = null;
app.whenReady().then(() => {
    createWindow();
    app.on('activate', () => {
        if (BrowserWindow.getAllWindows().length === 0) createWindow();
    });
});

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        websocket?.close();
        app.quit();
    };
});
